<template>
  <div>
    <div class="content">
      <OSSUpload v-on:onFileSelected="addIdCard" v-on:onImageDelete="deleteImage0" v-bind:imgList="imageList0" :content="'请将'+attachmentName['0']+'信息上传'"
        :title="'1.'+attachmentName['0']" />
      <OSSUpload v-on:onFileSelected="addIncomeCertificate" v-on:onImageDelete="deleteImage1" v-bind:imgList="imageList1" :content="'请将'+attachmentName['1']+'信息上传'"
        :title="'2.'+attachmentName['1']" />
      <OSSUpload v-on:onFileSelected="drivingLicence" v-on:onImageDelete="deleteImage2" v-bind:imgList="imageList2" :content="'请将'+attachmentName['2']+'信息上传'"
        :title="'3.'+attachmentName['2']" />
      <OSSUpload v-on:onFileSelected="drivingQualificationCertificate" v-bind:imgList="imageList3" v-on:onImageDelete="deleteImage3"
        :content="'请将'+attachmentName['3']+'信息上传'" :title="'4.'+attachmentName['3']" />
      <OSSUpload v-on:onFileSelected="personalLetterOfAuthorization" v-on:onImageDelete="deleteImage4" v-bind:imgList="imageList4"
        :content="'请将'+attachmentName['4']+'信息上传'" :title="'5.'+attachmentName['4']" />
      <OSSUpload v-on:onFileSelected="applicationForInstalment" v-bind:imgList="imageList5" v-on:onImageDelete="deleteImage5" :content="'请将'+attachmentName['5']+'信息上传'"
        :title="'6.'+attachmentName['5']" />
      <OSSUpload v-on:onFileSelected="noticeOfTransfer" v-bind:imgList="imageList6" v-on:onImageDelete="deleteImage6" :content="'请将'+attachmentName['6']+'信息上传'"
        :title="'7.'+attachmentName['6']" />
      <OSSUpload v-on:onFileSelected="termsOfApplicationForInstalment" v-bind:imgList="imageList7" v-on:onImageDelete="deleteImage7"
        :content="'请将'+attachmentName['7']+'信息上传'" :title="'8.'+attachmentName['7']" />
      <OSSUpload v-on:onFileSelected="creditCardApplicationForm" v-bind:imgList="imageList8" v-on:onImageDelete="deleteImage8"
        :content="'请将'+attachmentName['8']+'信息上传'" :title="'9.'+attachmentName['8']" />
    </div>
    <footer>
      <el-button @click="before()">上一步</el-button>
      <el-button @click.once="submitForm('ruleForm')" v-loading.fullscreen.lock="loading">下一步</el-button>
    </footer>
  </div>
</template>

<script>
  import eventVue from '../../assets/js/eventVue.js'
  import OSSUpload from "./OSSUpload";
  import OSS from 'ali-oss';
  import lrz from 'lrz'
  import axios from 'axios'


  /**
   * 将input type=file选择的文件转换成img标签可用的src
   * @param file
   * @returns {Promise<any>}
   */
  const convertFileToSrc = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = (e) => {
        resolve(e.target.result)
      }
      reader.readAsDataURL(file)
    })
  }

  /**
   * 获取阿里云OSS需要的token
   * @returns {Promise<*>}
   */
  const getOssStsToken = async (uri) => {
    let req = new Object()
    req['uploaddir'] = uri
    const result = await fetch('/gateway/fcs-api/getOssStsToken', {
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      },
      method: 'POST',
      body: JSON.stringify(req)
    })
    const res = await result.text()
    const obj = JSON.parse(res)
    return obj.policy
  }


  /**
   * 上传到阿里云方法。返回阿里云返回的参数
   * @param file  选择的file文件
   * @param progress  Thunk函数，设置进度条
   * @param uri
   * @returns {Promise<IterableIterator<*>|*>}
   */
  const uploadOSS = async (fname,file, progress, uri) => {
    const token = await getOssStsToken(uri)
    const data = token.host.replace('http://', '').split('.')
    const client = new OSS.Wrapper({
      region: data[1],
      accessKeyId: token.accessid,
      accessKeySecret: token.signature,
      stsToken: token.policy,
      bucket: data[0],
    })
    return client.multipartUpload(fname, file, {
      progress: progress
    })
  }


  /**
   * 上传到数据服务器
   * @param url 服务器地址
   * @param data  阿里云返回的信息拼装后的数据
   * @returns {Object}
   */
  const uploadServer = async (url, data) => {
    return await axios.post(url, data, {
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    }).then(res => {
      return res.data
    })
  }


  /**
   * 上传共同方法
   * @param url
   * @param file
   * @param imageList
   * @param uri
   * @returns {Object}
   */
  const addFile = async (url, file, imageList, uri) => {




    //1.现在集合中添加一个上传图片站位
    const imageItem = {
      src: '',
      percent: 0,
      isLoading: false,
      showDelete: false,
    }
    imageList.push(imageItem)


    //2.让图片先显示出来，把file格式转换成base64，设置到img标签的src上
    imageItem.src = await convertFileToSrc(file)


    //3.上传到阿里云图片服务器
    const progress = (percentage) => (callback) => {
      imageItem.percent = percentage * 100
      if (percentage === 1) {
        imageItem.showDelete = true
      }
      callback()
    }
    // 随机生成文件名
    function random_string(len) {
      len = len || 32
      const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
      const maxPos = chars.length
      let pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    }
    const fname=uri+'/'+random_string(6)+(new Date()).valueOf()+"."+file.name.split('.').pop();
    const zip = await lrz(file)
    const result = await uploadOSS(fname,zip.file, progress, uri)
    let resindex = result.name.lastIndexOf('/');
    let myname = result.name.substring(resindex);
    let globalname = myname.substring('1')
    let urisp = uri.split('/');
    let instNo = urisp[0];
    let applNo = urisp[1];
    let category1 = urisp[2];
    let category2 = urisp[3];
    let obj = new Object();
    obj['category2'] = category2;
    obj['category1'] = category1;
    obj['createId'] = sessionStorage.getItem('username')
    obj['instNo'] = instNo;
    obj['orderNo'] = applNo;
    obj['mediaUrl'] =fname;
    //4.上传到数据服务器
    const submit = await uploadServer(url, JSON.stringify(obj))
    submit.mediaUrl = uri + '/' + globalname
    return submit
  }
  /**
   * 删除数据服务器中的数据
   * @param url 服务器查询地址
   * @param urldel  服务器删除地址
   * @param instNo 机构号
   * @param applNo 订单号
   * @param mediaUrl 数据地址
   * @returns {Object}
   */
  const delFile = async (url, urldel, instNo, applNo, mediaUrl) => {
    let obj = new Object();
    obj['instNo'] = instNo;
    obj['orderNo'] = applNo;
    const item = await searchImg(url, JSON.stringify(obj))
    const len = item.length;
    for (let i = 0; i < len; i++) {
      if (item[i].mediaUrl == mediaUrl) {
        const delData = await delImg(urldel, JSON.stringify({
          id: item[i].id
        }))
      }
    }
  }
  /**
   * 查询数据服务器中的数据
   * @param url 服务器查询地址
   * @param data  参数包括订单号，机构号
   * @returns [Array]
   */
  const searchImg = async (url, data) => {
    return await axios.post(url, data, {
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    }).then(res => {
      return res.data.medias
    })
  }
  /**
   * 删除数据服务器中的数据
   * @param urldel 服务器删除地址
   * @param id  参数，指定删除数据的id
   * @returns {Object}
   */
  const delImg = async (urldel, id) => {
    return await axios.post(urldel, id, {
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    }).then(res => {
      return res.data
    })
  }
  export default {
    name: 'Upload',
    data: function () {
      return {
        loading: false,
        attachmentName: [],
        uri: [],
        imageList0: [],
        imageData0: [],
        imageList1: [],
        imageData1: [],
        imageList2: [],
        imageData2: [],
        imageList3: [],
        imageData3: [],
        imageList4: [],
        imageData4: [],
        imageList5: [],
        imageData5: [],
        imageList6: [],
        imageData6: [],
        imageList7: [],
        imageData7: [],
        imageList8: [],
        imageData8: [],
        selected: 0,
        active: 0,
        hasLoan: '是否已有贷款',
        loanMonthRepay: '已有贷款月还款额',
        hasHouseDataList: [],
        houseAreaList: [],
        housePriceList: [],
        hasCarList: [],
        carYearList: [],
        jobYearList: [],
        familiarConditionList: [],
        incomeList: [],
        hasLoanList: [],
        loanRapayList: [],
        ruleForm: {
          houseStatus: '',
          houseArea: '',
          houseAveragePrice: '',
          carRunStatus: '',
          carRunYear: '',
          carEntireYear: '',
          carFamiliarityConditions: '',
          familyMonthlyIncome: '',
          loanStatus: '',
          loanMonthRepay: '',
          //车辆信息
          carFuelType: '',
          carDeliveryDate: '',
          carCarRegisterNo: '',
          carCarBrand: '',
          carCarColor: '',
          carFare: '',
          carDispalcement: '',
          carFrameNo: '',
          carEngineNo: '',
          piecesStatus: '2',
          plate: '',
          carType: '',
          owner: '',
          address: '',
          issueDate: '',
          usingNature: '',
          identifty: '',
        },
        applNo: '',
        id: '',
        peieceId: '',
        instNo: ''
      }
    },
    mounted() {
      this.applNo = this.$route.query.applNo
      this.instNo = sessionStorage.getItem('instNo')
      var obj = {
        instNo: this.instNo,
        orderNo: this.applNo
      }
      this.axios.post('/fcs-api/selectMenu', JSON.stringify(obj), {
        headers: {
          'Content-Type': 'application/json;charset=UTF-8'
        }
      }).then(res => {
        const children = res.data.docTree[0].children
        const len = res.data.docTree[0].children.length
        const list = ['身份证','借款人收入证明','驾驶证','网约车驾驶员资格证','个人征信查询授权书','分期付款业务申请书','转让通知书','分期业务申请条款','信用卡申请表']
        for(let i= 0; i<len; i++){
          for(let j= 0; j<children[i].children.length;j++){
            if(list.some(data=> data===children[i].children[j].name)){
              this.attachmentName.push(children[i].children[j].name)
              this.uri.push(children[i].children[j].uri)
            }
          }
        }
    })
      // this.attachmentName.push('身份证', '借款人收入证明', '驾驶证', '网约车驾驶员资格证', '个人征信查询授权书', '分期付款业务申请书', '转让通知书', '分期业务申请条款',
      //   '信用卡申请表')
      // this.uri.push(`${this.instNo}/${this.applNo}/9010/9011`, `${this.instNo}/${this.applNo}/9040/9041`, `${this.instNo}/${this.applNo}/9050/9051`, `${this.instNo}/${this.applNo}/9050/9052`, `${this.instNo}/${this.applNo}/9060/9062`,
      //   `${this.instNo}/${this.applNo}/9060/9063`, `${this.instNo}/${this.applNo}/9060/9064`, `${this.instNo}/${this.applNo}/9060/9065`, `${this.instNo}/${this.applNo}/9060/9066`)
      // this.$store.commit('title', '附件上传')

      //获取车辆信息页面的数据
      eventVue.$on("carData", (data) => { //这里最好用箭头函数，不然this指向有问题
        this.ruleForm.carFuelType = data.carFuelType;
        this.ruleForm.carDeliveryDate = data.carDeliveryDate;
        this.ruleForm.carCarRegisterNo = data.carCarRegisterNo;
        this.ruleForm.carCarBrand = data.carCarBrand;
        this.ruleForm.carCarColor = data.carCarColor;
        this.ruleForm.carFare = data.carFare;
        this.ruleForm.carDispalcement = data.carDispalcement;
        this.ruleForm.carFrameNo = data.carFrameNo;
        this.ruleForm.carEngineNo = data.carEngineNo;
        this.ruleForm.plate = data.plate;
        this.ruleForm.carType = data.carType;
        this.ruleForm.owner = data.owner;
        this.ruleForm.address = data.address;
        this.ruleForm.issueDate = data.issueDate;
        this.ruleForm.usingNature = data.usingNature;
      });
      //
      //获取房产情况信息页面的数据
      eventVue.$on("propertyData", (data) => { //这里最好用箭头函数，不然this指向有问题
        this.ruleForm.houseStatus = data.houseStatus;
        this.ruleForm.houseArea = data.houseArea;
        this.ruleForm.houseAveragePrice = data.houseAveragePrice;
      });
      //
      //获取自有营运车辆情况信息页面的数据
      eventVue.$on("operatingData", (data) => { //这里最好用箭头函数，不然this指向有问题
        this.ruleForm.carRunStatus = data.carRunStatus;
        this.ruleForm.carRunYear = data.carRunYear;
        this.ruleForm.carEntireYear = data.carEntireYear;
        this.ruleForm.carFamiliarityConditions = data.carFamiliarityConditions;
      });
      //
      //获取已有贷款情况信息页面的数据
      eventVue.$on("loanData", (data) => { //这里最好用箭头函数，不然this指向有问题
        this.ruleForm.loanStatus = data.loanStatus;
        this.ruleForm.loanMonthRepay = data.loanMonthRepay;
      });
      //
    },
    components: {
      OSSUpload
    },
    methods: {
      addIdCard: async function (file) {
        const a = addFile('/fcs-api/afterUpload', file, this.imageList0, this.uri[0],)
        a.then(res => {
          if (res.success == true) {
            this.imageData0.push(res.mediaUrl)
          }
        })
      },
      addIncomeCertificate: async function (file) {
        const a = addFile('/fcs-api/afterUpload', file, this.imageList1, this.uri[1])
        a.then(res => {
          if (res.success == true) {
            this.imageData1.push(res.mediaUrl)
          }
        })
      },
      drivingLicence: async function (file) {
        const a = addFile('/fcs-api/afterUpload', file, this.imageList2, this.uri[2])
        a.then(res => {
          if (res.success == true) {
            this.imageData2.push(res.mediaUrl)
          }
        })
      },
      drivingQualificationCertificate: async function (file) {
        const a = addFile('/fcs-api/afterUpload', file, this.imageList3, this.uri[3])
        a.then(res => {
          if (res.success == true) {
            this.imageData3.push(res.mediaUrl)
          }
        })
      },
      personalLetterOfAuthorization: async function (file) {
        const a = addFile('/fcs-api/afterUpload', file, this.imageList4, this.uri[4])
        a.then(res => {
          if (res.success == true) {
            this.imageData4.push(res.mediaUrl)
          }
        })
      },
      applicationForInstalment: async function (file) {
        const a = addFile('/fcs-api/afterUpload', file, this.imageList5, this.uri[5])
        a.then(res => {
          if (res.success == true) {
            this.imageData5.push(res.mediaUrl)
          }
        })
      },
      noticeOfTransfer: async function (file) {
        const a = addFile('/fcs-api/afterUpload', file, this.imageList6, this.uri[6])
        a.then(res => {
          if (res.success == true) {
            this.imageData6.push(res.mediaUrl)
          }
        })
      },
      termsOfApplicationForInstalment: async function (file) {
        const a = addFile('/fcs-api/afterUpload', file, this.imageList7, this.uri[7])
        a.then(res => {
          if (res.success == true) {
            this.imageData7.push(res.mediaUrl)
          }
        })
      },
      creditCardApplicationForm: async function (file) {
        const a = addFile('/fcs-api/afterUpload', file, this.imageList8, this.uri[8])
        a.then(res => {
          if (res.success == true) {
            this.imageData8.push(res.mediaUrl)
          }
        })
      },
      deleteImage0: function (index) {
        this.imageList0.splice(index, 1);
        const del = delFile('/fcs-api/getMediaUrls', '/fcs-api/restDeleteMedia', this.instNo, this.applNo, this.imageData0)
      },
      deleteImage1: function (index) {
        this.imageList1.splice(index, 1);
        const del = delFile('/fcs-api/getMediaUrls', '/fcs-api/restDeleteMedia', this.instNo, this.applNo, this.imageData1)
      },
      deleteImage2: function (index) {
        this.imageList2.splice(index, 1);
        const del = delFile('/fcs-api/getMediaUrls', '/fcs-api/restDeleteMedia', this.instNo, this.applNo, this.imageData2)
      },
      deleteImage3: function (index) {
        this.imageList3.splice(index, 1);
        const del = delFile('/fcs-api/getMediaUrls', '/fcs-api/restDeleteMedia', this.instNo, this.applNo, this.imageData3)
      },
      deleteImage4: function (index) {
        this.imageList4.splice(index, 1);
        const del = delFile('/fcs-api/getMediaUrls', '/fcs-api/restDeleteMedia', this.instNo, this.applNo, this.imageData4)
      },
      deleteImage5: function (index) {
        this.imageList5.splice(index, 1);
        const del = delFile('/fcs-api/getMediaUrls', '/fcs-api/restDeleteMedia', this.instNo, this.applNo, this.imageData5)
      },
      deleteImage6: function (index) {
        this.imageList6.splice(index, 1);
        const del = delFile('/fcs-api/getMediaUrls', '/fcs-api/restDeleteMedia', this.instNo, this.applNo, this.imageData6)
      },
      deleteImage7: function (index) {
        this.imageList7.splice(index, 1);
        const del = delFile('/fcs-api/getMediaUrls', '/fcs-api/restDeleteMedia', this.instNo, this.applNo, this.imageData7)
      },
      deleteImage8: function (index) {
        this.imageList8.splice(index, 1);
        const del = delFile('/fcs-api/getMediaUrls', '/fcs-api/restDeleteMedia', this.instNo, this.applNo, this.imageData8)
      },
      submitForm(formName) {
        const productCode = sessionStorage.getItem('productId')
        this.loading = true;
        // if (!this.imageList0.length || !this.imageList1.length || !
        //     this.imageList2.length || !this.imageList3.length || !this.imageList4.length || !this.imageList5.length || !this.imageList6.length || !
        //     this.imageList7.length || !this.imageList8.length) {
        //     this.active = 4;
        //     this.selected = 4;
        //     this.$message.error('附件不能为空，每种附件至少上传一张');
        //     this.$emit('nextStep', this.active);
        //     this.$emit('nextStep2', this.selected);
        //   return;
        // }
        var obj = new Object();
        var detail = new Object();
        obj["productCode"] = productCode;
        obj["id"] = this.id;
        obj["pieceId"] = this.$route.query.pieceId;
        obj["gmtCreate"] = (new Date()).toString;
        obj["gmtUpdate"] = (new Date()).toString;
        obj["isdelete"] = 0;
        detail["houseStatus"] = this.ruleForm.houseStatus;
        detail["houseArea"] = this.ruleForm.houseArea;
        detail["houseAveragePrice"] = this.ruleForm.houseAveragePrice;
        detail["carRunStatus"] = this.ruleForm.carRunStatus;
        detail["carRunYear"] = this.ruleForm.carRunYear;
        detail["carEntireYear"] = this.ruleForm.carEntireYear;
        detail["carFamiliarityConditions"] = this.ruleForm.carFamiliarityConditions;
        detail["familyMonthlyIncome"] = this.ruleForm.familyMonthlyIncome;
        detail["loanStatus"] = this.ruleForm.loanStatus;
        detail["loanMonthRepay"] = this.ruleForm.loanMonthRepay;
        //设置车辆信息
        detail["carFuelType"] = this.ruleForm.carFuelType;
        detail["carDeliveryDate"] = this.ruleForm.carDeliveryDate;
        detail["carCarRegisterNo"] = this.ruleForm.carCarRegisterNo;
        detail["carCarBrand"] = this.ruleForm.carCarBrand;
        detail["carCarColor"] = this.ruleForm.carCarColor;
        detail["carFare"] = this.ruleForm.carFare;
        detail["carDispalcement"] = this.ruleForm.carDispalcement;
        detail["carFrameNo"] = this.ruleForm.carFrameNo;
        detail["carEngineNo"] = this.ruleForm.carEngineNo;
        detail["plate"] = this.ruleForm.plate;
        detail["carType"] = this.ruleForm.carType;
        detail["owner"] = this.ruleForm.owner;
        detail["address"] = this.ruleForm.address;
        detail["issueDate"] = this.ruleForm.issueDate;
        detail["usingNature"] = this.ruleForm.usingNature;
        detail["identify"] = this.ruleForm.carFrameNo;
        obj["detail"] = detail;
        this.axios.post("/zyapply-api/detailPieces/save", obj, {
          headers: {
            "Content-Type": "application/json;charset=UTF-8"
          }
        }).then((result) => {
          if (result.status == 200 && result.data.status == 200) {
            this.$store.commit('title', '完成')
            this.active = 6;
            this.selected = 5;
            this.loading = false;
            this.$message({
              message: '创建成功！',
              type: 'success'
            });
            this.$emit('nextStep', this.active);
            this.$emit('nextStep2', this.selected);
          } else {
            this.active = 4;
            this.selected = 4;
            this.loading = false;
            this.$message.error('创建失败！');
            this.$emit('nextStep', this.active);
            this.$emit('nextStep2', this.selected);
          }

        })
      },
      before() {
        this.$store.commit('title', '已有贷款情况')
        this.active = 3;
        this.selected = 3;
        this.$emit('beforeStep',this.active);
        this.$emit('beforeStep2',this.selected);
      }
    },
  }

</script>

<style scoped>
  .content {
    margin-top: 20px;
    margin-bottom: 80px;
  }

  footer {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    height: 80px;
    background: #ddd;
  }

</style>
